package wpwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import wpwork.entity.KshGroupEntity;
import wpwork.entity.KshMessageEntity;
import wpwork.entity.KshMessageEntity;
import wpwork.entity.WorkPersonJobEntity;
import wpwork.mapper.KshMessageMapper;
import wpwork.model.*;
import wpwork.permission.entity.UserEntity;
import wpwork.permission.mapper.UserMapper;
import wpwork.redisEntity.UserInfo;
import wpwork.service.IKshMessageService;
import wpwork.service.KshGroupService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class KshMessageServiceImpl
        extends ServiceImpl<KshMessageMapper, KshMessageEntity> implements IKshMessageService {

    @Autowired
    private KshGroupService groupService;
    @Autowired
    private UserMapper userMapper;

    //Redis发布于
    @Autowired
    private DataInteractionService dataInteractionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMessage(SendMessageRequestDTO request) {
        if (!request.isValid()) {
            throw new RuntimeException("参数校验失败");
        }

        if ("person".equals(request.getType())) {
            // 个人消息：直接创建一条记录
            boolean result = createPersonalMessage(request);
            if (result){
                UserEntity userEntity = userMapper.selectById(request.getToUserId());
                List<UserInfo> userList = new ArrayList<>();
                userList.add(new UserInfo(request.getToUserId(), userEntity.getAccount()));
                dataInteractionService.handleAICall("747384603941027201", request.getMessage(), userList);
            }
            return result;
        } else if ("group".equals(request.getType())) {
            // 群组消息：为群组中每个用户创建一条记录
            boolean result = createGroupMessages(request);
            if (result){
                List<String> groupMembers = getGroupMembers(request.getToUserId());
                List<UserInfo> userList = new ArrayList<>();
                for (String userId : groupMembers) {
                    UserEntity userEntity = userMapper.selectById(userId);
                    userList.add(new UserInfo(userId, userEntity.getAccount()));
                }
                dataInteractionService.handleAICall("747384603941027201", request.getMessage(), userList);
            }
            return result;
        } else {
            throw new RuntimeException("不支持的消息类型: " + request.getType());
        }
    }

    /**
     * 创建个人消息
     */
    private boolean createPersonalMessage(SendMessageRequestDTO request) {
        KshMessageEntity message = new KshMessageEntity();
        BeanUtils.copyProperties(request, message);

        // 设置默认值
        message.setIsRead(0);
        message.setEnabledMark(1);
        message.setGroupId(null); // 个人消息没有群组ID
        message.setDeleteMark(0);
        message.setCreatorTime(LocalDateTime.now());
        return this.save(message);
    }

    /**
     * 创建群组消息
     */
    private boolean createGroupMessages(SendMessageRequestDTO request) {
        // 获取群组成员列表
        List<String> groupMembers = getGroupMembers(request.getToUserId());

        if (groupMembers.isEmpty()) {
            throw new RuntimeException("群组中没有成员");
        }

        List<KshMessageEntity> messages = new ArrayList<>();
        for (String memberId : groupMembers) {
            // 排除自己
            if (memberId.equals(request.getFromUserId())) {
                continue;
            }

            KshMessageEntity message = new KshMessageEntity();
            BeanUtils.copyProperties(request, message);

            // 设置群组消息的特殊属性
            message.setToUserId(memberId); // 接收人是群组成员
            message.setGroupId(request.getToUserId()); // 群组ID
            message.setIsRead(0);
            message.setEnabledMark(1);
            message.setDeleteMark(0);
            message.setCreatorTime(LocalDateTime.now());
            messages.add(message);
        }

        return !messages.isEmpty() && this.saveBatch(messages);
    }

    @Override
    public List<String> getGroupMembers(String groupId) {
        List<String> groupUserIds = groupService.getGroupUserIds(Long.valueOf(groupId));
//        getGroupUserIds
        return groupUserIds;
    }

    @Override
    public List<MessageResponseDTO2> instantMessage(String receivePerson, String sendPerson, String sendType, String keyword, String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate;
        Date endDate;
        LambdaQueryWrapper<KshMessageEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (!"".equals(startTime) && "".equals(endTime)){
            try {
                startDate = sdf.parse(startTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(KshMessageEntity::getCreatorTime, startDate)
            );
        } else if ( "".equals(startTime) && !"".equals(endTime)) {
            try {
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.le(KshMessageEntity::getCreatorTime, endDate)
            );
        } else if ( !"".equals(startTime) && !"".equals(endTime)) {
            try {
                startDate = sdf.parse(startTime);
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            queryWrapper.and(wrapper ->
                    wrapper.ge(KshMessageEntity::getCreatorTime, startDate)
            ).and(wrapper ->
                    wrapper.le(KshMessageEntity::getCreatorTime, endDate)
            );
        }
        if(!"".equals(keyword)){
            queryWrapper.like(KshMessageEntity::getMessage, keyword);
        }
        if(!"".equals(sendType)){
            queryWrapper.eq(KshMessageEntity::getType, sendType);
        }
        List<KshMessageEntity> kshMessageEntities = this.list(queryWrapper);
        List<MessageResponseDTO2> messageResponseDTO2s = entityToDTO2(kshMessageEntities,receivePerson,sendPerson);
        return messageResponseDTO2s;
    }

    @Override
    public boolean markMessagesAsRead(MarkAsReadRequestDTO request) {
        // 查询符合条件的未读消息
        QueryWrapper<KshMessageEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("f_fromuserid", request.getFromUserId())
                .eq("f_touserid", request.getToUserId())
                .eq("f_isread", 0)
                .eq("f_delete_mark", 0);

        List<KshMessageEntity> unreadMessages = this.list(wrapper);

        if (unreadMessages.isEmpty()) {
            return true; // 没有需要更新的消息
        }

        // 批量更新为已读状态
        for (KshMessageEntity message : unreadMessages) {
            message.setIsRead(1);
            message.setReadTime(LocalDateTime.now());
        }

        return this.updateBatchById(unreadMessages);
    }

    @Override
    public List<KshMessageEntity> queryMessages(QueryMessageRequestDTO request) {
        QueryWrapper<KshMessageEntity> wrapper = new QueryWrapper<>();

        if ("person".equals(request.getType())) {
            // 个人消息查询：双向查询
            wrapper.and(w -> w
                            .eq("f_fromuserid", request.getFromUserId())
                            .eq("f_touserid", request.getToUserId())
                            .or()
                            .eq("f_fromuserid", request.getToUserId())
                            .eq("f_touserid", request.getFromUserId())
                    )
                    .eq("f_type", "person");
        } else if ("group".equals(request.getType())) {
            // 群组消息查询：当前用户接收到的所有群组消息
//            wrapper.eq("f_touserid", request.getToUserId())
            wrapper.eq("f_groupid", request.getToUserId())
                    .eq("f_type", "group");

            // 如果指定了发送人，则添加发送人条件
            if (StringUtils.hasText(request.getFromUserId())) {
                wrapper.eq("f_fromuserid", request.getFromUserId());
            }
        } else {
            // 查询所有类型的消息
            wrapper.and(w -> w
                    .and(w1 -> w1
                            .eq("f_fromuserid", request.getFromUserId())
                            .eq("f_touserid", request.getToUserId())
                    )
                    .or(w2 -> w2
                            .eq("f_fromuserid", request.getToUserId())
                            .eq("f_touserid", request.getFromUserId())
                            .eq("f_type", "person")
                    )
                    .or(w3 -> w3
                            .eq("f_touserid", request.getToUserId())
                            .eq("f_type", "group")
                    )
            );
        }

        // 只查询未删除的消息
        wrapper.eq("f_delete_mark", 0);

        // 按创建时间倒序排列
        wrapper.orderByAsc("f_creator_time");

        return this.list(wrapper);
    }

    @Override
    public List<KshMessageEntity> getUnreadMessages(String toUserId) {
        QueryWrapper<KshMessageEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("f_touserid", toUserId)
                .eq("f_isread", 0)
                .eq("f_delete_mark", 0)
                .orderByDesc("f_creator_time");

        return this.list(wrapper);
    }

    public List<MessageResponseDTO2> entityToDTO2(List<KshMessageEntity> kshMessageEntities, String receivePerson, String sendPerson){
        List<MessageResponseDTO2> messageResponseDTO2s = new ArrayList<>();
        for (KshMessageEntity kshMessageEntity : kshMessageEntities) {
            MessageResponseDTO2 entity = new MessageResponseDTO2();
            UserEntity fromUserEntity = userMapper.selectById(kshMessageEntity.getFromUserId());
            UserEntity touserEntity = userMapper.selectById(kshMessageEntity.getToUserId());
            if(touserEntity == null || fromUserEntity == null){
                continue;
            }
            if(kshMessageEntity.getType() == "group"){
                KshGroupEntity byId = groupService.getById(kshMessageEntity.getGroupId());
                entity.setGroupName(byId.getName());
            }
            if(receivePerson!=null || "".equals(receivePerson)){
                if(!fromUserEntity.getRealName().contains(receivePerson) && !touserEntity.getRealName().contains(receivePerson)){
                    continue;
                }
            }
            if(sendPerson!=null || "".equals(sendPerson)){
                if(!fromUserEntity.getRealName().contains(sendPerson) && !touserEntity.getRealName().contains(sendPerson)){
                    continue;
                }
            }
            entity.setId(kshMessageEntity.getId());
            entity.setType(kshMessageEntity.getType());
            entity.setGroupId(kshMessageEntity.getGroupId());
            entity.setFromUserId(kshMessageEntity.getFromUserId());
            entity.setFromUserName(fromUserEntity.getRealName());
            entity.setToUserId(kshMessageEntity.getToUserId());
            entity.setToUserName(touserEntity.getRealName());
            entity.setMessage(kshMessageEntity.getMessage());
            entity.setIsRead(kshMessageEntity.getIsRead());
            entity.setReadTime(kshMessageEntity.getReadTime());
            entity.setRemark(kshMessageEntity.getRemark());
            entity.setCreatorTime(kshMessageEntity.getCreatorTime());
            messageResponseDTO2s.add(entity);
        }
        return messageResponseDTO2s;
    }
}
